<template>
  <div>
    <a-button @click="handleStateFilter('state_draft')"> 待处理 </a-button>
    <!-- <a-button @click="handleStateFilter('state_error')"> error </a-button> -->
    <a-button @click="handleStateFilter('')"> 全部 </a-button>
    <a-button @click="handleStateFilter('state_done')"> 已完成 </a-button>

    <sale2fp ref="refWizard" @change="handelChange" />

    <a-input v-model="filter_partner_id_value"> </a-input>
    <a-button @click="handleFilter"> 开票客户模糊搜索 </a-button>

    <a-select
      v-model="filter_invoice_type_value"
      placeholder="Please select"
      style="width: 50%"
      @change="handleInVoiceTypeChange"
    >
      <a-select-option v-for="op in filter_invoice_type_selection" :key="op[0]">
        {{ op[1] }}
      </a-select-option>
    </a-select>

    <a-divider type="vertical" />
    <a-button @click="delete_sale_order"> 删除 </a-button>

    <a-table
      :row-selection="rowSelection"
      :columns="columns"
      :data-source="records"
      rowKey="id"
      :scroll="{ x: 1500, y: 300 }"
    >
      <!-- <div slot="expandedRowRender" slot-scope="record">
        {{ record }}
      </div> -->
      <a-table
        slot="expandedRowRender"
        slot-scope="record"
        :columns="line_ids__Columns"
        :data-source="record.line_ids__records"
        :pagination="false"
        rowKey="id"
        style="background: lightyellow"
      >
      </a-table>
    </a-table>

    <a-modal
      title="开票客户维护"
      :width="1200"
      :visible="showPtnFormView"
      @ok="showPtnFormView = false"
      @cancel="showPtnFormView = false"
      :footer="null"
    >
      <PtnFormView ref="refPtnFormView" @closeModal="closePtnAction" />
    </a-modal>

    <a-modal
      title="开票商品信息维护"
      :width="1200"
      :visible="showProductFormView"
      @ok="showProductFormView = false"
      @cancel="showProductFormView = false"
      :footer="null"
    >
      <ProductFormView
        :productInfo="productInfo"
        :ncInfo="ncInfo"
        @closeModal="closePrdctAction"
      />
    </a-modal>
  </div>
</template>

<script>
function sleep(millisecond) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, millisecond)
  })
}

import api from '@/odoorpc'
import simpleTreeMixin from '../simpleTreeMixin'

import sale2fp from './sale2fp.vue'
import PtnFormView from './ptn_form_view.vue'
import ProductFormView from './product_form_view.vue'

export default {
  name: 'SaleTreeView',

  components: { sale2fp, PtnFormView, ProductFormView },
  mixins: [simpleTreeMixin],
  props: {},

  data() {
    return {
      line_ids_fields: {},
      filter_invoice_type_value: null,
      filter_partner_id_value: '',

      showPtnFormView: false,
      showProductFormView: false,

      productInfo: {},
      ncInfo: {}
    }
  },

  computed: {
    filter_invoice_type_selection() {
      return (this.search_items.group1 || {}).selection || []
    },

    line_ids__Columns() {
      //       order_id: {},
      // product_categ_id: { string: '开票商品类别' },
      // product_id: { string: '商品' },
      // product_spec: { string: '规格' },
      // product_uom: { string: '单位' },
      // tax_ratio: { string: '税率' },
      // quantity: { string: '数量' },
      // price_unit: { string: '含税单价' },
      // amount_discount: { string: '折扣' },
      // amount_untaxed: { string: '不含税金额' },
      // amount_tax: { string: '税' },
      // note: { string: '备注' }

      return [
        // {
        //   title: 'id',
        //   dataIndex: 'id',
        //   key: 'id'
        // },

        {
          title: '开票商品状态',
          dataIndex: 'product_state',
          key: 'product_state',
          customRender: (value, record) => {
            const that = this

            if (value === 'draft') {
              return (
                <a-button onClick={() => that.handelCilckProductState(record)}>
                  验证产品{' '}
                </a-button>
              )
            } else {
              return '已完成'
            }
          },
          ellipsis: false,
          align: 'center'
        },

        {
          title: '税务商品',
          dataIndex: 'vat_product_id',
          key: 'vat_product_id',
          customRender: value => (value ? value[1] : ''),
          ellipsis: false,
          align: 'center'
        },

        {
          title: '商品',
          dataIndex: 'product_id',
          key: 'product_id',
          customRender: value => (value ? value[1] : ''),
          ellipsis: false,
          align: 'center'
        },

        {
          title: '规格',
          dataIndex: 'product_spec',
          key: 'product_spec',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '单位',
          dataIndex: 'product_uom',
          key: 'product_uom',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          key: 'quantity',
          ellipsis: false,
          align: 'center'
        },

        {
          title: '含税单价',
          dataIndex: 'price_unit',
          key: 'price_unit',
          ellipsis: false,
          align: 'center'
        },

        {
          title: '税率',
          dataIndex: 'tax_ratio',
          key: 'tax_ratio',
          ellipsis: false,
          align: 'center'
        },

        {
          title: '无税金额',
          dataIndex: 'amount_untaxed',
          key: 'amount_untaxed',
          ellipsis: false,
          align: 'center'
        },

        {
          title: '税额',
          dataIndex: 'amount_tax',
          key: 'amount_tax',
          ellipsis: false,
          align: 'center'
        },

        {
          title: '含税金额',
          dataIndex: 'amount_total',
          key: 'amount_total',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '折扣',
          dataIndex: 'amount_discount',
          key: 'amount_discount',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '备注',
          dataIndex: 'note',
          key: 'note',
          ellipsis: false,
          align: 'center'
        }
      ]
    },

    columns() {
      return [
        {
          title: '开票客户',
          dataIndex: 'partner_state',
          key: 'partner_state',
          align: 'center',
          customRender: (value, record) => {
            const that = this

            if (value === 'draft') {
              return (
                <a-button onClick={() => that.handelCilckPartnerState(record)}>
                  验证客户{' '}
                </a-button>
              )
            } else {
              return '已完成'
            }

            // const meta = this.fields.partner_state
            // const elm = meta.selection.find(item => item[0] === value)
            // return elm ? elm[1] : ''
          },
          ellipsis: false
        },
        {
          dataIndex: 'invoice_type',
          key: 'invoice_type',
          title: '发票类型',
          align: 'center',
          customRender: value => {
            const meta = this.fields['invoice_type']
            const elm = meta.selection.find(item => item[0] === value)
            return elm ? elm[1] : ''
          },
          ellipsis: false
        },
        // {
        //   dataIndex: 'client_order_ref',
        //   key: 'client_order_ref',
        //   title: 'NC发票PK',
        //   align: 'center',
        //   ellipsis: false
        // },
        {
          dataIndex: 'name',
          key: 'name',
          title: '订单号',
          align: 'center',
          ellipsis: false
        },
        {
          dataIndex: 'date_order',
          key: 'date_order',
          title: '日期',
          align: 'center',
          ellipsis: false
        },
        {
          dataIndex: 'partner_id',
          key: 'partner_id',
          title: '客户',
          align: 'center',
          customRender: value => (value ? value[1] : ''),
          ellipsis: false
        },
        {
          dataIndex: 'fp_partner_id',
          key: 'fp_partner_id',
          title: '开票客户',
          align: 'center',
          customRender: value => (value ? value[1] : ''),
          ellipsis: false
        },

        {
          dataIndex: 'company_id',
          key: 'company_id',
          title: '公司',
          align: 'center',
          customRender: value => (value ? value[1] : ''),
          ellipsis: false
        },
        {
          dataIndex: 'user_id',
          key: 'user_id',
          title: '用户',
          align: 'center',
          customRender: value => (value ? value[1] : ''),
          ellipsis: false
        },

        {
          dataIndex: 'amount_total',
          key: 'amount_total',
          title: '金额',
          align: 'center',
          ellipsis: false
        },
        {
          dataIndex: 'state',
          key: 'state',
          title: '状态',
          align: 'center',
          customRender: value => {
            const meta = this.fields['state']
            const elm = meta.selection.find(item => item[0] === value)
            return elm ? elm[1] : ''
          },
          ellipsis: false
        }
      ]
    }
  },

  created() {},

  mounted() {},

  methods: {
    async handelCilckPartnerState(record) {
      console.log('=== goto 开票客户页面 ===', record.id, record.partner_id)
      const pid = record.partner_id[0]

      this.showPtnFormView = true
      await sleep(100)

      this.$refs.refPtnFormView.init(pid)
    },

    async handelCilckProductState(record) {
      console.log(
        '---------- 123 -------=== product ===',
        record.id,
        record.product_id
      )
      const prdctid = record.product_id[0]

      this.showProductFormView = true
      await sleep(100)

      const res = await api.env.model('fp.product').read(prdctid, {
        fields: [
          'nc_product_ids',
          'nc_state',
          'vat_product_id',
          'vat_product_code',
          'vat_product_name',
          'code',
          'name',
          'spec',
          'uom'
        ]
      })

      const product_info = res[0]
      const nc_ids = product_info.nc_product_ids

      const res2 = await api.env.model('fp.nc.ods.product').read(nc_ids, {
        fields: [
          'state',
          'name',
          'code',
          'spec',
          'uom',
          'vat_product_code',
          'vat_product_name'
        ]
      })

      const nc_info = res2[0]
      console.log('--=- product_info =-=', product_info)
      console.log('--=- nc_info =-=', nc_info)

      // //
      this.productInfo = product_info
      this.ncInfo = nc_info

      // 打开 弹窗。显示  product_info
      //   点击 审核通过 按钮 call:
      //     await api.env.model('fp.nc.ods.product').write( nc_info.id, {state: 'done' })
      // 关闭 弹窗
      // 然后 在刷新 本页面
    },
    init_filter() {
      this.search_values = this.treeview.search_change(
        this.search_items.group1,
        ['state_draft']
      )
    },

    async _initMe_relation(view, fields_list) {
      const fields = view.fields
      const relations = {}
      for (const fld of fields_list) {
        const field_info = fields[fld]
        const relation = api.env.relation(field_info, {
          parent: view.view_info
        })

        await relation.load_views()

        relations[fld] = relation
      }

      return relations
    },

    async _initMe_data_relation(relations, values, fields_list) {
      const result = {}
      for (const fld of fields_list) {
        const relation_value = values[fld]
        const relation_records = await relations[fld].tree.read(relation_value)

        result[fld] = relation_records
      }

      return result
    },

    async search_relation() {
      const relations = await this._initMe_relation(this.treeview, ['line_ids'])

      this.line_ids_fields = relations.line_ids.tree.fields

      const line_ids = this.records.reduce((acc, one) => {
        return [...acc, ...one.line_ids]
      }, [])

      const realtion_data = await this._initMe_data_relation(
        relations,
        { line_ids },
        ['line_ids']
      )

      this.records = this.records.map(item => {
        const line_ids__records = realtion_data.line_ids.filter(line =>
          item.line_ids.includes(line.id)
        )

        return { ...item, line_ids__records }
      })
    },

    async rowSelected() {
      this.showWizard()
    },

    async showWizard() {
      console.log(this.activeIds)
      console.log(this)
      // initMe
      await this.$refs.refWizard.initMe(this.activeIds)
    },

    async handleInVoiceTypeChange(invoice_type) {
      // this.search_values = this.treeview.search_change(
      //   this.search_items.partner_id,
      //   [{ string: val_p, value: val_p }]
      // );

      this.search_values = this.treeview.search_change(
        this.search_items.group4,
        [invoice_type]
      )

      this.records = await this.treeview.search_read()
      await this.search_relation()
    },

    async handleFilter() {
      const val_p = this.filter_partner_id_value
      this.search_values = this.treeview.search_change(
        this.search_items.partner_id,
        [{ string: val_p, value: val_p }]
      )

      this.records = await this.treeview.search_read()
      await this.search_relation()
    },

    async handleStateFilter(state_value) {
      this.search_values = this.treeview.search_change(
        this.search_items.group1,
        [state_value]
      )

      this.records = await this.treeview.search_read()
      await this.search_relation()
    },

    async delete_sale_order() {
      console.log(this.activeIds)
      await this.treeview.unlink(this.activeIds)

      this.records = await this.treeview.search_read()
      await this.search_relation()
    },

    async handelChange() {
      this.activeIds = []

      this.records = await this.treeview.search_read()
      await this.search_relation()
    },
    async closePtnAction(val) {
      this.records = await this.treeview.search_read()
      await this.search_relation()

      this.showPtnFormView = val
    },
    async closePrdctAction(val) {
      this.records = await this.treeview.search_read()
      await this.search_relation()
      this.showProductFormView = val
    }
  }
}
</script>

<style type="text/css"></style>
